const db = require("../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config");
//todo 新增时候自动添加自己的id
// 权限管理 根据

// 首页数据信息
exports.getDataInfo = (req, res) => {
  let obj = {}
  let promiseAll = []

  //user
  let userpms = new Promise((resolve, reject) => {
    const usersql = `select count(*) as usernumber
    from user where user__id = ${req.user.user_id}`;
    db.query(usersql, function (err, results) {
      if (err) return res.cc(err);
      if (results.length < 1) return res.cc("失败！");
      obj.usernumber = results[0].usernumber
      resolve();
    });
  })
  promiseAll.push(userpms)

  //article
  let articlepms = new Promise((resolve, reject) => {
    const articlesql = `select count(*) as articlenumber
    from article  where user_id = ${req.user.user_id}`;
    db.query(articlesql, function (err, results) {
      if (err) return res.cc(err);
      if (results.length < 1) return res.cc("失败！");
      obj.articlenumber = results[0].articlenumber
      resolve();
    });
  })
  promiseAll.push(articlepms)

  //comment
  let commentpms = new Promise((resolve, reject) => {
    const commentsql = `select count(*) as commentnumber
    from comment  where user_id = ${req.user.user_id}`;
    db.query(commentsql, function (err, results) {
      if (err) return res.cc(err);
      if (results.length < 1) return res.cc("失败！");
      obj.commentnumber = results[0].commentnumber
      resolve();
    });
  })
  promiseAll.push(commentpms)

  //classification
  let classificationpms = new Promise((resolve, reject) => {
    const classificationsql = `select count(*) as classificationnumber
      from classification where user_id = ${req.user.user_id}`;
    db.query(classificationsql, function (err, results) {
      if (err) return res.cc(err);
      if (results.length < 1) return res.cc("失败！");
      obj.classificationnumber = results[0].classificationnumber
      resolve();
    });
  })
  promiseAll.push(classificationpms)

  Promise.all(promiseAll).then(() => {
    //navigation
    new Promise((resolve, reject) => {
      const navigationsql = `select count(*) as navigationnumber
      from navigation where user_id = ${req.user.user_id}`;
      db.query(navigationsql, function (err, results) {
        if (err) return res.cc(err);
        if (results.length < 1) return res.cc("失败！");
        obj.navigationnumber = results[0].navigationnumber
        res.rt({
          message: "成功！",
          res: obj
        });
      });
    })
  })
};
// 添加文章
exports.addArticle = (req, res) => {
  const sql = `insert into article set ?`;
  db.query(sql, req.body, (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt("新增成功！");
  });
};
// 删除文章
exports.delArticle = (req, res) => {
  //根据id查询文章列表中是否包含生活和留言的,删除没有的
  let list = JSON.parse(req.body.list)
  let sql = `SELECT article_id FROM article WHERE article_id IN (?) and is_live = 0 and is_speak = 0 and user_id = ${req.user.user_id}`
  db.query(sql, [list], function (err, results) {
    if (err) return res.cc(err);
    if (results.length < 1) return res.cc("失败1！");
    list = results.map((v) => v.article_id)
    const sql = `delete from article where article_id in (?)`;
    db.query(sql, [list], function (err, results) {
      if (err) return res.cc(err);
      if (results.length < 1) return res.cc("失败2！");
      res.rt("删除成功！");
    });
  });
};
// 修改文章
exports.setArticle = (req, res) => {
  const sql = `update article set ? where article_id=? and user_id = ${req.user.user_id}`;
  db.query(sql, [req.body, req.body.article_id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt("成功！");
  });
};
// 分类增删改
exports.addClass = (req, res) => {
  const sql = `insert into classification set ?`;
  db.query(sql, req.body, (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt("新增成功！");
  });
};
exports.delClass = (req, res) => {
  const sql = `delete from classification where class_id in (?) and user_id = ${req.user.user_id} and is_live = 0`;
  db.query(sql, [req.body.list], function (err, results) {
    if (err) return res.cc(err);
    if (results.length < 1) return res.cc("失败！");
    res.rt('删除成功！');
  });
};
exports.setClass = (req, res) => {
  const sql = `update classification set ? where class_id=? and user_id = ${req.user.user_id}`;
  db.query(sql, [req.body, req.body.class_id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt("成功！");
  });
};
// 修改页面数据
exports.setPageinfo = (req, res) => {
  const sql = `update pagedata set ? where page_id=? and user_id = ${req.user.user_id}`;
  db.query(sql, [req.body], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    return res.rt("成功！");
  });
};
// 用户增删改查
exports.addUser = (req, res) => {
  const userinfo = req.body;
  if (!userinfo.username || !userinfo.password) {
    return res.cc("用户名或密码不能为空！");
  }
  const sql = `select * from user where username=?`;
  db.query(sql, [userinfo.username], function (err, results) {
    if (err) return res.cc(err.message);
    if (results.length > 0) return res.cc("用户名被占用，请更换其他用户名！");
    // 对用户的密码,进行 bcrype 加密，返回值是加密之后的密码字符串
    userinfo.password = bcrypt.hashSync(userinfo.password, 10);
    const sql2 = "insert into user set ?";
    db.query(sql2, userinfo, function (err, results) {
      if (err) return res.cc(err.message);
      if (results.affectedRows < 1) {
        return res.cc("注册用户失败，请稍后再试！",);
      }
      res.rt("注册成功！");
    }
    );
  });
};
exports.delUser = (req, res) => {
  if (req.body.list.includes(0)) return res.cc('不能删除！')
  const sql = `delete from user where user_id in (?)`;
  db.query(sql, [req.body.list], function (err, results) {
    if (err) return res.cc(err);
    if (results.length < 1) return res.cc("失败！");
    res.rt('删除成功！');
  });
};
exports.setUser = (req, res) => {
  const sql = `update user set ? where user_id=?`;
  if (req.body.password) {
    req.body.password = bcrypt.hashSync(req.body.password, 10);
  }
  db.query(sql, [req.body, req.body.user_id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("修改用户信息失败！");
    res.rt("修改用户基本信息成功！");
  });
};
exports.getUser = (req, res) => {
  const pagesize = parseInt(req.query.pagesize) || 1;
  const pagenum = (parseInt(req.query.pagenum) - 1) * pagesize || 0;
  const field = req.query.field || ''
  const sql = `select user_id,username,nickname,birthday,sex,autograph,user_pic,is_delete,cellphone
  from user
  where user_id != 0 and (username like '%${field}%' or nickname like '%${field}%' or cellphone like '%${field}%')
  LIMIT ? , ? `;
  db.query(sql, [pagenum, pagesize], function (err, results) {
    if (err) return res.cc(err);
    if (results.length < 1) return res.cc("失败！");
    db.query(
      `select count(*) as total from user where user_id != 0 and (username like '%${field}%' or nickname like '%${field}%' or cellphone like '%${field}%')`,
      function (err, data) {
        res.rt({
          total: data[0].total,
          status: 0,
          message: "获取成功！",
          results,
        });
      }
    );
  });
};
// 评论删改查
exports.delComment = (req, res) => {
  const sql = `delete from comment where comment_id in (?)`;
  db.query(sql, [req.body.list], function (err, results) {
    if (err) return res.cc(err);
    if (results.length < 1) return res.cc("失败！");
    res.rt('删除成功！');
  });
};
exports.setComment = (req, res) => {
  const sql = `update comment set ? where comment.comment_id = ?`;
  db.query(sql, [req.body, req.body.comment_id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    return res.rt("成功！");
  });
};
exports.getComment = (req, res) => {
  const pagesize = parseInt(req.query.pagesize) || 1;
  const pagenum = (parseInt(req.query.pagenum) - 1) * pagesize || 0;
  let field = req.query.field ? req.query.field : ''
  const sql = `
  SELECT comment
	.*,
	article.title,
	user.nickname
	
FROM
	comment INNER JOIN article
	INNER JOIN user ON comment.articleid = article.article_id 
	AND comment.userid = user.user_id 
  where comment.content like '%${field}%'
	LIMIT ?,
	?
  `;
  db.query(sql, [pagenum, pagesize], function (err, results) {
    // 执行 SQL 语句失败
    if (err) return res.cc(err);
    // 执行 SQL 语句成功，但是查询到数据条数不等于 1
    if (results.length < 1) return res.cc("失败！");
    // 返回

    db.query(`select count(*) as total from comment where comment.content like '%${field}%'`, function (err, data) {
      res.rt({
        total: data[0].total,
        message: "获取成功！",
        results,
      });
    });
  });
};

// 导航增删改查
exports.addNav = (req, res) => {
  const sql = `insert into navigation set ?`;
  db.query(sql, req.body, (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt("新增成功！");
  });
};
exports.delNav = (req, res) => {
  const sql = `delete from navigation where nav_id in (?)`;
  db.query(sql, [req.body.list], function (err, results) {
    if (err) return res.cc(err);
    if (results.length < 1) return res.cc("失败！");
    res.rt("删除成功！");
  });
};
exports.setNav = (req, res) => {
  const sql = `update navigation set ? where nav_id=?`;
  db.query(sql, [req.body, req.body.nav_id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt("成功！");
  });
};

//修改系统配置
exports.setSystem = (req, res) => {
  const sql = `update pagedata set ? where page_id=1`;
  db.query(sql, [req.body], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("失败！");
    res.rt({
      message: "修改成功！",
    });
  });
};

//修改用户信息
exports.setUserInfo = (req, res) => {
  const sql = `update user set ? where user_id=?`;
  if (req.body.password) {
    req.body.password = bcrypt.hashSync(req.body.password, 10);
  }
  db.query(sql, [req.body, req.body.user_id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows < 1) return res.cc("修改用户基本信息失败！");
    res.rt("修改用户基本信息成功！");
  });
};

//修改管理员密码
exports.setAdminPwd = (req, res) => {
  if (!req.body.newpwd === req.body.repeatpwd) {
    return res.cc("输入不一致");
  } else {
    db.query(`select * from user where user_id=0`, (err, results) => {
      const compareResult = bcrypt.compareSync(
        req.body.oldpwd,
        results[0].password
      );
      if (!compareResult) {
        return res.cc("密码错误！");
      }
      //修改密码
      let newpwd = bcrypt.hashSync(req.body.newpwd, 10);
      db.query(`update user set password=? where user_id=0`, newpwd, (err, results) => {
        if (err) return res.cc(err);
        if (results.length < 1) return res.cc("失败！");
        res.rt("修改成功！");
      }
      );
    });
  }
};